package com.personal.dao.sqlgenerator;

import com.personal.dao.bean.BaseModel;
import com.personal.dao.configuration.Configuration;
import com.personal.dao.dialect.DaoDialect;
import com.personal.dao.exception.NoPrimaryKeyException;
import com.personal.dao.metadata.DataBaseTableMetadata;
import com.personal.dao.reflection.MetaObject;
import com.personal.dao.sql.BaseSql;
import com.personal.dao.sql.Sql;

/**
 * 通过条件查询个数
 * @author cuibo
 *
 */
public class UpdateByPrimaryKeySelective<T extends BaseModel> extends BaseSqlGenerator<T>
{
 
    public UpdateByPrimaryKeySelective(T value, DataBaseTableMetadata<T> metadata, DaoDialect dialect)
    {
        super(value, metadata);
        this.dialect = dialect;
    }
    
    
    @Override
    public Sql generate()
    {
        checkPrimaryKey();
        BaseSql update = generateValue(false, true);
        StringBuilder sql = new StringBuilder("update ").append(metadata.getTableName());
        sql.append(" set ").append(update.getSql()).append(" where ").append(metadata.getPrimaryKey().getColumnName()).append(" = ?");
        MetaObject metaObject = Configuration.getInstance().newMetaObject(this.value);
        Object pk = metaObject.getValue(metadata.getPrimaryKey().getFieldName());
        if (pk == null)
        {
            throw new NoPrimaryKeyException(value + "的主键为空！");
        }
        update.getValues().add(pk);
        return new BaseSql(sql.toString(), update.getValues());
    }

}
